package com.ruoyi.web.controller.system;

import java.util.Map;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

/**
 * 数据字典信息
 * 
 * @author ruoyi
 */
@Api(tags = "字典类型管理")
@RestController
@RequestMapping("/system/dict/type")
public class SysDictTypeController extends BaseController
{
    @Autowired
    private ISysDictTypeService dictTypeService;

    @ApiOperation(value = "获取字典类型列表", notes = "获取系统字典类型列表，支持分页、条件过滤查询")
    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDictType dictType)
    {
        startPage();
        // 自动设置当前登录用户的租户ID，确保数据按租户隔离
        if (dictType.getTenantId() == null) {
            dictType.setTenantId(SecurityUtils.getTenantIdSafe());
        }
        List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
        return getDataTable(list);
    }

    @ApiOperation(value = "导出字典类型", notes = "导出字典类型数据，支持条件过滤")
    @Log(title = "字典类型", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:dict:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDictType dictType)
    {
        // 自动设置当前登录用户的租户ID，确保数据按租户隔离
        if (dictType.getTenantId() == null) {
            dictType.setTenantId(SecurityUtils.getTenantIdSafe());
        }
        List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
        ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class);
        util.exportExcel(response, list, "字典类型");
    }

    /**
     * 查询字典类型详细
     */
    @ApiOperation(value = "获取字典类型详细信息", notes = "根据ID获取字典类型详细信息")
    @ApiImplicitParam(name = "dictId", value = "字典ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermi('system:dict:query')")
    @GetMapping(value = "/{dictId}")
    public AjaxResult getInfo(@PathVariable Long dictId)
    {
        return success(dictTypeService.selectDictTypeById(dictId));
    }

    /**
     * 新增字典类型
     */
    @ApiOperation(value = "新增字典类型", notes = "新增字典类型")
    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @Log(title = "字典类型", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDictType dict)
    {
        if (!dictTypeService.checkDictTypeUnique(dict))
        {
            return error("新增字典'" + dict.getDictName() + "'失败，字典类型已存在");
        }
        dict.setCreateBy(getUsername());
        return toAjax(dictTypeService.insertDictType(dict));
    }

    /**
     * 修改字典类型
     */
    @ApiOperation(value = "修改字典类型", notes = "修改字典类型")
    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @Log(title = "字典类型", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDictType dict)
    {
        if (!dictTypeService.checkDictTypeUnique(dict))
        {
            return error("修改字典'" + dict.getDictName() + "'失败，字典类型已存在");
        }
        dict.setUpdateBy(getUsername());
        return toAjax(dictTypeService.updateDictType(dict));
    }

    /**
     * 删除字典类型
     */
    @ApiOperation(value = "删除字典类型", notes = "删除字典类型")
    @ApiImplicitParam(name = "dictIds", value = "字典ID列表", required = true, dataType = "long", paramType = "path", allowMultiple = true, dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictIds}")
    public AjaxResult remove(@PathVariable Long[] dictIds)
    {
        dictTypeService.deleteDictTypeByIds(dictIds);
        return success();
    }

    /**
     * 刷新字典缓存
     */
    @ApiOperation(value = "刷新字典缓存", notes = "刷新字典缓存")
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public AjaxResult refreshCache()
    {
        dictTypeService.resetDictCache();
        return success();
    }

    /**
     * 获取字典选择框列表
     */
    @ApiOperation(value = "获取字典选择框列表", notes = "获取所有字典类型列表（下拉框使用）")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll();
        return success(dictTypes);
    }

    /**
     * 同步字典数据到目标租户
     */
    @ApiOperation(value = "同步字典数据到目标租户", notes = "将字典数据从源租户同步到目标租户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "sourceTenantId", value = "源租户ID", required = true, dataType = "long", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "targetTenantId", value = "目标租户ID", required = true, dataType = "long", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "dictIds", value = "字典类型ID列表", required = true, dataType = "List", dataTypeClass = List.class)
    })
    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @Log(title = "字典类型", businessType = BusinessType.UPDATE)
    @PostMapping("/syncToTenant")
    public AjaxResult syncToTenant(@RequestBody Map<String, Object> params)
    {
        Long sourceTenantId = Long.valueOf(params.get("sourceTenantId").toString());
        Long targetTenantId = Long.valueOf(params.get("targetTenantId").toString());
        List<?> dictIdList = (List<?>) params.get("dictIds");
        
        // 修复ArrayStoreException问题：手动转换每个元素为Long类型
        Long[] dictIds = new Long[dictIdList.size()];
        for (int i = 0; i < dictIdList.size(); i++) {
            dictIds[i] = Long.valueOf(dictIdList.get(i).toString());
        }
        
        int count = dictTypeService.syncDictToTenant(sourceTenantId, targetTenantId, dictIds);
        return success("成功同步" + count + "个字典");
    }
    
    /**
     * 校验字典类型是否唯一
     */
    @ApiOperation(value = "校验字典类型是否唯一", notes = "校验字典类型在当前租户下是否唯一")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "dictType", value = "字典类型", required = true, dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "dictId", value = "字典ID（编辑时传入）", required = false, dataType = "Long", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "tenantId", value = "租户ID", required = false, dataType = "Long", dataTypeClass = Long.class)
    })
    @GetMapping("/checkUnique")
    public AjaxResult checkUnique(@RequestParam String dictType, 
                                  @RequestParam(required = false) Long dictId,
                                  @RequestParam(required = false) Long tenantId)
    {
        SysDictType dict = new SysDictType();
        dict.setDictType(dictType);
        dict.setDictId(dictId);
        
        // 如果没有传入租户ID，使用当前用户的租户ID
        if (tenantId == null)
        {
            tenantId = SecurityUtils.getTenantIdSafe();
        }
        dict.setTenantId(tenantId);
        
        boolean isUnique = dictTypeService.checkDictTypeUnique(dict);
        return AjaxResult.success(isUnique);
    }
}
